/**
 *
 * @file utils.c
 *
 * @brief Some conversion functions, memory management etc...
 *
 * $Id: utils.c 69 2009-01-08 09:29:03Z henri.doreau $
 */

/*
 * This file is part of Tsar.
 *
 * Tsar is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tsar is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tsar.  If not, see <http://www.gnu.org/licenses/>.
 */


#include <utils.h>
#include <output.h>

/* Convert a string to an unsigned long int */
int str2ulong( char * str, unsigned long * dstNumber )
{
    /* Followig code come from securecoding.cert.org */
    int retVal;
    unsigned long tmpLong;
    char *end_ptr;

    errno = 0;

    tmpLong = strtoul( str, &end_ptr, 10 );

    if ( tmpLong == LONG_MAX && errno != 0 )
    {
        perror( "strtol" );
        retVal = 1;
    }
    else if ( end_ptr == str )
    {
        fprintf( stderr,"error encountered during conversion\n" );
        retVal = 2;
    }
    else if ( '\0' != *end_ptr )
    {
        fprintf( stderr, "extra characters on input line\n" );
        retVal = 3;
    }
    else
    {
        *dstNumber = ( unsigned long )tmpLong;
        retVal = 0;
    }

    return retVal;
}

/*
 * System function wrappers
 * XXX: they all die on error!!
 */

FILE * Fopen( char * filename, char * mode )
{
    FILE * fd;

    fd = fopen( filename, mode );
    if ( fd == NULL )
    {
        die( "fopen" );
    }
    return fd;
}

void * Malloc( size_t size )
{
    void * p;

    p = malloc( size );
    if ( p == NULL )
    {
        die( "malloc" );
    }
    return p;
}

void Free( void * p )
{
    if ( p )
        free( p );
}

void * Realloc( void * ptr, size_t size )
{
    void * p;

    p = realloc( ptr, size );
    if ( p == NULL )
    {
        die( "realloc" );
    }
    return p;
}

